import { expandScope } from '../utils/commonApi';

// 获取网格配置
export function getGrid({ config = {} }) {
  const style = config.option.style;
  return {
    top: +style.grid.top,
    left: +style.grid.left,
    right: +style.grid.right,
    bottom: +style.grid.bottom,
  };
}
// 获取图例
export function getLegend({ config = {}, field = 'extra' }) {
  const extra = field
    .split('.')
    .reduce((prev, curr) => prev[curr], config.option);
  const legendPositionObj = {};
  if (extra.legendPosition === 'top') {
    legendPositionObj.top = extra.legendTop;
    legendPositionObj.left = extra.legendLeft;
  } else if (extra.legendPosition === 'bottom') {
    legendPositionObj.bottom = extra.legendBottom;
    legendPositionObj.left = extra.legendLeft;
  }
  const names = (extra.legendName || '')
    .replace(/，|\.|\;/g, ',')
    .split(',')
    .filter(v => v);
  return {
    show: extra.showLegend,
    type: 'scroll',
    ...legendPositionObj,
    icon: extra.legendIcon,
    data: names.map(v => ({ name: v })),
    itemGap: extra.legendGap,
    itemWidth: extra.legendWidth,
    itemHeight: extra.legendHeight,
    textStyle: {
      color: extra.legendTextColor,
      fontSize: extra.legendTextFontSize,
      padding: [0, 0, 0, 10],
    },
  };
}
// 获取标题
export function getTitleUnit({ config = {} }) {
  const style = config.option?.style;
  const unitOffset = (style.unitOffset || '-4.5,-9').split(',');
  return {
    subtext: style.unit ? `(单位/${style.unit})` : '',
    right: +unitOffset[0],
    top: +unitOffset[1],
    subtextStyle: {
      color: style.unitColor,
      fontSize: +style.unitFontSize,
    },
  };
}
// 获取提示配置
export function getTooltip({ config = {} }) {
  const style = config.option.style;
  return {
    ...(style.tooltip.execFn
      ? {
        show: style.tooltip.show,
        trigger: 'axis',
        appendToBody: true,
        confine: true,
        textStyle: {
          color: style.tooltip?.textStyle?.color,
          fontSize: style.tooltip?.textStyle?.fontSize
        },
        backgroundColor: style.tooltip.color,
        formatter: params => {
          const fun = new Function('data', 'style', style.tooltip.execFn);
          return fun(params, style);
        },
      }
      : {
        show: style.tooltip.show,
        backgroundColor: style.tooltip.color,
        appendToBody: true,
        confine: false,
        textStyle: {
          color: style.tooltip?.textStyle?.color,
          fontSize: style.tooltip?.textStyle?.fontSize
        }
      }),
  };
}
// 获取x轴配置
export function getXAxis({ config = {}, options = {} }) {
  const style = config.option.style;
  let { type = 'category' } = options;

  // 为了兼容已经使用的环境
  let formatter = null;
  let formatter1 = style.x.axisLabel.formatter;
  let formatter2 = style.x.axisLabel.formatter2;
  if (formatter2 && formatter2.length) {
    formatter = (value, index) => {
      const fun = new Function('value', 'index', formatter2);
      return fun(value, index);
    };
  } else if (formatter1 && formatter1.length) {
    formatter = formatter1;
  }
  return {
    type,
    show: style.x.show,
    position: style.x.position,
    axisLine: {
      show: style.x.axisLine.show,
      lineStyle: {
        width: +style.x.axisLine.width,
        color: +style.x.axisLine.color,
      },
    },
    splitLine: {
      show: style.x.splitLine.show,
      interval: +style.x.splitLine.interval,
      lineStyle: {
        width: +style.x.splitLine.width,
        color: style.x.splitLine.color,
        type: style.x.splitLine.type,
      },
    },
    axisLabel: {
      show: style.x.axisLabel.show,
      margin: style.x.axisLabel.margin,
      width: +style.x.axisLabel.width,
      overflow: style.x.axisLabel.overflow,
      rotate: +style.x.axisLabel.rotate,
      formatter: formatter,
      interval:
        (!isNaN(style.x.axisLabel.interval)
          ? +style.x.axisLabel.interval
          : style.x.axisLabel.interval) || 0,
      color: style.x.axisLabel.color,
      fontSize: +style.x.axisLabel.fontSize,
      fontFamily: style.x.axisLabel.fontFamily,
    },
    axisTick: {
      show: false,
    },
  };
}
// 获取y轴配置
export function getYAxis({ config = {}, options = {} }) {
  const businessKey = config?.dataSource?.businessKey;
  const style = config.option.style;
  let { yValKey = '' } = options;
  let yMinAndMax = {};
  if (businessKey) {
    const data = config.option.data || [];
    if (yValKey) {
      if (style.y.useMin) {
        const calcMin = Math.min(...data.map(v => v[yValKey]));
        yMinAndMax.min = Math.ceil(
          expandScope(calcMin, 'min', style.y.minRate),
        );
      }
      if (style.y.useMax) {
        const calcMax = Math.max(...data.map(v => v[yValKey]));
        yMinAndMax.max = Math.ceil(
          expandScope(calcMax, 'max', style.y.maxRate),
        );
      }
      if (yMinAndMax.min && yMinAndMax.max) {
        yMinAndMax.interval = Math.ceil(
          (yMinAndMax.max - yMinAndMax.min) / (style.y.splitInterval || 1),
        );
      }
    }
  }

  let nameOptions = {};
  try {
    nameOptions = JSON.parse(style.y.nameOptions);
  } catch (e) {
    console.log('nameOptions: ', e)
  }

  // 为了兼容已经使用的环境
  let formatter = null;
  let formatter1 = style.y.axisLabel.formatter;
  let formatter2 = style.y.axisLabel.formatter2;
  if (formatter2 && formatter2.length) {
    formatter = (value, index) => {
      const fun = new Function('value', 'index', formatter2);
      return fun(value, index);
    };
  } else if (formatter1 && formatter1.length) {
    formatter = formatter1;
  }

  return [
    {
      show: style.y.show,
      ...nameOptions,
      axisLine: {
        show: style.y.axisLine.show,
        lineStyle: {
          width: +style.y.axisLine.width,
          color: style.y.axisLine.color,
        },
      },
      splitLine: {
        show: style.y.splitLine.show,
        interval: +style.y.splitLine.interval,
        lineStyle: {
          width: +style.y.splitLine.width,
          color: style.y.splitLine.color,
          type: style.y.splitLine.type,
        },
      },
      axisLabel: {
        // formatter: style.y.axisLabel.formatter,
        formatter: formatter,
        show: style.y.axisLabel.show,
        margin: style.y.axisLabel.margin,
        color: style.y.axisLabel.color,
        fontSize: +style.y.axisLabel.fontSize,
        rotate: +style.y.axisLabel.rotate,
        interval:
          (!isNaN(style.y.axisLabel.interval)
            ? +style.y.axisLabel.interval
            : style.y.axisLabel.interval) || 0,
        fontFamily: style.y.axisLabel.fontFamily,
      },
      ...yMinAndMax,
      minInterval: 1,
    },
  ];
}
// 获取极坐标系配置
export function getPolar({ config = {} }) {
  const style = config.option.style;
  const center = (style.polar.center || '50%,50%').split(',');
  return {
    center: center,
    radius: style.polar.radius,
  };
}
// 获取极坐标系的径向轴配置
export function getRadiusAxis({ config = {}, options = {} }) {
  return getXAxis({ config, options });
}
// 获取雷达图坐标系配置
export function getRadar({ config = {} }) {
  const style = config.option.style;
  let {
    titleColor = '#C1E9FF',
    titleFontSize = 18,
    titleFontFamily = 'ping-fang',
    titleFontWeight = 700,
    titleWrap = 7,
    showValue = 0,
    valueColor = '#ffffff',
    valueFontSize = 24,
    valueFontFamily = 'dinpro-bold',
    valueAlign = 'center',
    valueFontWeight = 700,
    valueUnit = 'km',
    center = '50%,50%',
    radius = '65%',
    startAngle = 120,
  } = style.radar;
  let {
    alternateColor1 = 'transparent',
    alternateColor2 = 'rgba(56,154,255,0.1)',
  } = style.radar.splitArea;
  const _center = (center || '50%,50%').split(',');
  return {
    axisName: {
      rich: {
        name: {
          fontSize: titleFontSize,
          color: titleColor,
          fontFamily: titleFontFamily,
          fontWeight: titleFontWeight,
        },
        count: {
          color: valueColor,
          fontSize: valueFontSize,
          fontFamily: valueFontFamily,
          fontWeight: valueFontWeight,
          align: valueAlign,
          lineHeight: '15',
        },
      },
      formatter: (name, item) => {
        let name1 = name.slice(0, titleWrap);
        let name2 = name.slice(titleWrap);
        let nameNew = name1 + '\n' + name2;
        let str = `{name|${nameNew}}`;
        if (showValue == 1) {
          str += `\n{count|${item.count}${valueUnit || ''}}`;
        }
        return str;
      },
    },
    shape: 'polygon',
    center: _center,
    radius: radius,
    startAngle: startAngle,
    scale: true,
    axisTick: { show: false },
    axisLine: {
      lineStyle: {
        width: style.radar.axisLine.width,
        color: style.radar.axisLine.color,
      },
    },
    splitLine: {
      show: true,
      lineStyle: {
        width: style.radar.splitLine.width,
        color: style.radar.splitLine.color, // 设置网格的颜色
      },
    },
    splitArea: {
      show: true,
      areaStyle: {
        color: [alternateColor1, alternateColor2],
      },
    },
  };
}
